import { useState, useEffect } from "react";
import { useLocation, useNavigate, useSearchParams } from "react-router-dom";
import { Input, Select, List, Pagination, Tag, Button, Spin, message } from "antd";
import { 
  SearchOutlined, 
  ArrowRightOutlined, 
  ClockCircleOutlined, 
  DownloadOutlined, 
  FileTextOutlined 
} from "@ant-design/icons";
import { generateMockTorrents, categories } from "@mock";
import "./search.styl";

const CategoryIcon = ({ category }) => {
  const icons = {
    movie: <FileTextOutlined />,
    music: <FileTextOutlined />,
    game: <FileTextOutlined />,
    software: <FileTextOutlined />,
  };
  return icons[category] || <FileTextOutlined />;
};

const TorrentSearch = () => {
  const location = useLocation();
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const [loading, setLoading] = useState(false);
  const [results, setResults] = useState([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  // 修正后的分类选项配置
  const categoryOptions = [
    { value: "all", label: "全部" },
    ...categories.map(c => ({ 
      value: c.value,
      label: (
        <span className="category-option">
          <CategoryIcon category={c.value} />
          <span className="category-label">{c.label}</span>
        </span>
      )
    }))
  ];

  // 从URL参数获取初始值
  const initialKeyword = searchParams.get("q") || "";
  const initialCategory = searchParams.get("category") || "all";

  const [searchState, setSearchState] = useState({
    keyword: initialKeyword,
    category: initialCategory,
  });

  const formatBytes = (bytes) => {
    if (bytes === 0) return "0 B";
    const k = 1024;
    const units = ["B", "KB", "MB", "GB", "TB"];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + units[i];
  };

  const handleSearch = () => {
    navigate({
      pathname: "/search",
      search: `?q=${encodeURIComponent(searchState.keyword)}&category=${searchState.category}`
    });
    setPagination(prev => ({ ...prev, current: 1 }));
  };

  useEffect(() => {
    const fetchResults = async () => {
      try {
        setLoading(true);
        const mockData = generateMockTorrents();
        
        const filteredData = mockData.filter(item => {
          const keywordMatch = searchState.keyword 
            ? item.name.toLowerCase().includes(searchState.keyword.toLowerCase()) || 
              (item.description && item.description.toLowerCase().includes(searchState.keyword.toLowerCase()))
            : true;
            
          const categoryMatch = searchState.category === 'all' 
            ? true 
            : item.category === searchState.category;

          return keywordMatch && categoryMatch;
        });

        const enhancedData = filteredData.map(item => ({
          ...item,
          cover: item.cover || `https://picsum.photos/80/80?${item.id}`,
          seeders: Math.floor(Math.random() * 1000),
          createdAt: new Date(item.createdAt).toLocaleDateString(),
          size: formatBytes(item.size),
          downloads: item.downloads || Math.floor(Math.random() * 1000)
        }));
        
        setResults(enhancedData.slice(
          (pagination.current - 1) * pagination.pageSize,
          pagination.current * pagination.pageSize
        ));
        setPagination(prev => ({
          ...prev,
          total: filteredData.length
        }));
      } catch (error) {
        message.error("数据加载失败");
      } finally {
        setLoading(false);
      }
    };

    fetchResults();
  }, [location.search, pagination.current]);

  return (
    <div className="search-page">
      <div className="search-header">
        <Input.Group compact className="search-bar">
          <Select
            value={searchState.category}
            options={categoryOptions}
            onChange={value => setSearchState(prev => ({ ...prev, category: value }))}
            dropdownMatchSelectWidth={200}
            className="category-select"
            optionLabelProp="label"
          >
            {categoryOptions.map(option => (
              <Select.Option 
                key={option.value} 
                value={option.value}
                label={
                  <span className="category-label">
                    <CategoryIcon category={option.value} />
                    {option.value === "all" ? "全部" : categories.find(c => c.value === option.value)?.label}
                  </span>
                }
              >
                {option.label}
              </Select.Option>
            ))}
          </Select>
          <Input
            placeholder="输入关键词搜索资源..."
            value={searchState.keyword}
            onChange={e => setSearchState(prev => ({ ...prev, keyword: e.target.value }))}
            onPressEnter={handleSearch}
            allowClear
            className="search-input"
          />
          <Button 
            type="primary" 
            icon={<SearchOutlined />} 
            onClick={handleSearch}
            className="search-button"
          >
            搜索
          </Button>
        </Input.Group>
      </div>

      <Spin spinning={loading} tip="搜索中...">
        <List
          itemLayout="vertical"
          dataSource={results}
          renderItem={item => (
            <List.Item
              key={item.id}
              className="torrent-item"
              actions={[
                <div key="stats" className="meta-stats">
                  <span className="stat">
                    <ClockCircleOutlined /> {item.seeders} 做种
                  </span>
                  <span className="stat">
                    <DownloadOutlined /> {item.downloads} 下载
                  </span>
                </div>,
                <Tag 
                  key="category"
                  icon={<CategoryIcon category={item.category} />}
                  color="geekblue"
                  className="category-tag"
                >
                  {categories.find(c => c.value === item.category)?.label}
                </Tag>
              ]}
            >
              <List.Item.Meta
                avatar={
                  <div className="torrent-cover">
                    {item.cover ? (
                      <img src={item.cover} alt={item.name} />
                    ) : (
                      <FileTextOutlined style={{ fontSize: 40, color: '#1890ff' }} />
                    )}
                  </div>
                }
                title={
                  <Button 
                    type="link" 
                    onClick={() => navigate(`/torrent/${item.id}`)}
                    className="torrent-title"
                  >
                    {item.name}
                  </Button>
                }
                description={
                  <div className="torrent-description">
                    <div className="size-info">
                      <span>{item.size}</span>
                      <span className="upload-time">
                        {item.createdAt}
                      </span>
                    </div>
                    {item.description && (
                      <div className="excerpt">{item.description}</div>
                    )}
                    <div className="tag-container">
                      {item.tags?.map((tag, i) => (
                        <Tag key={i} color={i % 2 ? 'geekblue' : 'green'}>{tag}</Tag>
                      ))}
                    </div>
                  </div>
                }
              />
              <Button 
                type="primary" 
                size="small" 
                onClick={() => navigate(`/torrent/${item.id}`)}
                className="detail-btn"
              >
                查看详情 <ArrowRightOutlined />
              </Button>
            </List.Item>
          )}
        />

        <div className="pagination">
          <Pagination
            current={pagination.current}
            pageSize={pagination.pageSize}
            total={pagination.total}
            showSizeChanger={false}
            onChange={(page) => setPagination(prev => ({ ...prev, current: page }))}
            style={{ marginTop: 24, textAlign: 'center' }}
          />
        </div>
      </Spin>
    </div>
  );
};

export default TorrentSearch;